package com.eonmind.ai.core.draw.schedule.handler;

import cn.hutool.core.net.url.UrlBuilder;
import cn.hutool.json.JSONUtil;
import com.eonmind.ai.config.AiConfig;
import com.eonmind.ai.core.draw.platform.mdJounery.MdDrawService;
import com.eonmind.ai.core.draw.platform.mdJounery.model.MdTaskQueryResponse;
import com.eonmind.ai.mapper.AiDrawMapper;
import com.eonmind.common.contract.data.response.ResponseEntity;
import com.eonmind.common.contract.enums.ai.AiArtworkStatusEnum;
import com.eonmind.common.contract.enums.oss.OssUploadEnum;
import com.eonmind.common.contract.enums.user.NoticeTypesEnum;
import com.eonmind.common.contract.oss.OssUtil;
import com.eonmind.common.provider.entity.ai.AiArtwork;
import com.eonmind.common.provider.entity.ai.AiDrawPlatform;
import com.eonmind.user.contract.api.UserNoticeFeignService;
import com.eonmind.user.contract.dto.UserNoticeDto;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.jetbrains.annotations.NotNull;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.net.URL;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Component
public class MjSyncProgressHandler {

    @Resource
    private AiDrawMapper aiDrawMapper;

    @Resource
    private MdDrawService mdDrawService;


    public void syncProgress(AiDrawPlatform aiDrawPlatform, List<AiArtwork> aiArtworkList) {
        List<String> taskIds = aiArtworkList.stream().map(AiArtwork::getTaskId).distinct().toList();
        if (taskIds.isEmpty()) {
            return;
        }
        log.info("[MJ draw 同步任务] 开始同步任务进度：{}", taskIds);
        List<MdTaskQueryResponse> mdTaskQueryResponses = mdDrawService.queryBatchDrawTask(aiDrawPlatform, taskIds);
        Map<String, MdTaskQueryResponse> queryResponseMap = mdTaskQueryResponses.stream()
                .collect(Collectors.toMap(MdTaskQueryResponse::getId, t -> t));
        List<AiArtwork> aiArtworks = aiArtworkList.stream()
                .map(t -> {
                    MdTaskQueryResponse mdTaskQueryResponse = queryResponseMap.get(t.getTaskId());
                    if (mdTaskQueryResponse == null) {
                        return t;
                    }
                    return mdDrawService.syncMjArtworkProgress(t, mdTaskQueryResponse);
                })
                .toList();
        aiDrawMapper.updateBatchByIds(aiArtworks);
    }

}